package priv.stones.controller.administrate;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import priv.stones.common.annotation.CommitLog;
import priv.stones.common.utils.Result;
import priv.stones.entity.SysMenu;
import priv.stones.entity.SysRole;
import priv.stones.service.SysMenuService;
import priv.stones.service.SysRoleService;

import java.util.Date;
import java.util.List;

/**
 * @Author: Stones
 * @Description:
 * @Date: 2017/10/16 19:46
 */
@Controller
@RequestMapping("/administrate/role")
public class RoleController extends BaseController {

    @Autowired
    private SysRoleService sysRoleService;
    @Autowired
    private SysMenuService sysMenuService;

    /**
     * 列表
     *
     * @param model
     * @param pageNo
     * @param pageSize
     * @return
     */
    @RequestMapping("")
    @RequiresPermissions("sys:role:list")
    public String List(Model model
            , @RequestParam(value = "pageNo", defaultValue = "1") int pageNo
            , @RequestParam(value = "pageSize", defaultValue = "10") int pageSize) {
        EntityWrapper<SysRole> ew = new EntityWrapper<>();
        ew.orderBy("createtime", true);
        Page<SysRole> data = sysRoleService.selectPage(new Page<>(pageNo, pageSize), ew);
        model.addAttribute("data", data.getRecords());
        model.addAttribute("pageNo", pageNo);
        model.addAttribute("pageSize", pageSize);
        model.addAttribute("dataCount", data.getTotal());
        return FreeMarkerViewResult("role/list", model);
    }

    /**
     * 编辑
     *
     * @param model
     * @param id
     * @return
     */
    @RequestMapping("/edit")
    public String Edit(Model model, @RequestParam(value = "id", defaultValue = "") String id) {
        SysRole sysRole;
        //拥有的角色
        List<String> ownMenus = null;
        if (!StringUtils.isBlank(id)) {
            sysRole = sysRoleService.selectById(id);
            ownMenus = sysRoleService.selectMenuIdsById(id);
        } else {
            sysRole = new SysRole();
            sysRole.setStatus(1);
        }
        model.addAttribute("data", sysRole);
        //输出菜单树
        List<SysMenu> menus = sysMenuService.selectList(new EntityWrapper<SysMenu>()
                .eq("status", 1)
                .orderBy("sort", true));
        JSONArray jsonArray = new JSONArray();
        for (SysMenu menu : menus) {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("id", menu.getId());
            jsonObject.put("pId", menu.getParentid());
            jsonObject.put("name", menu.getName());
            jsonObject.put("open", "true");
            if (ownMenus != null) {
                if (ownMenus.contains(menu.getId())) {
                    jsonObject.put("checked", "true");
                }
            }
            jsonArray.add(jsonObject);
        }
        model.addAttribute("menus", JSON.toJSONString(jsonArray));
        return FreeMarkerViewResult("role/edit", model);
    }

    @RequestMapping(value = "/edit/insert", method = RequestMethod.POST)
    @RequiresPermissions("sys:role:insert")
    @CommitLog("添加角色")
    @ResponseBody
    public Result Insert(SysRole sysRole, @RequestParam(value = "menus[]", required = false) String[] menus) {
        if (sysRoleService.selectCount(new EntityWrapper<SysRole>().eq("name", sysRole.getName())) > 0) {
            return Result.Error("名称已存在");
        }
        sysRole.setCreatetime(new Date());
        boolean result = sysRoleService.insert(sysRole);
        sysRoleService.relateMenus(menus, sysRole.getId());
        return result ? Result.Ok() : Result.Error();
    }

    @RequestMapping(value = "/edit/update", method = RequestMethod.POST)
    @RequiresPermissions("sys:role:update")
    @CommitLog("修改角色")
    @ResponseBody
    public Result Update(SysRole sysRole, @RequestParam(value = "menus[]", required = false) String[] menus) {
        sysRole.setName(null);
        boolean result = sysRoleService.updateById(sysRole);
        sysRoleService.relateMenus(menus, sysRole.getId());
        return result ? Result.Ok() : Result.Error();
    }

    @RequestMapping(value = "/delete", method = RequestMethod.POST)
    @RequiresPermissions("sys:role:delete")
    @CommitLog("删除角色")
    @ResponseBody
    public Result Delete(String id) {
        sysRoleService.delete(id);
        return Result.Ok();
    }

}
